﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for Util
/// </summary>
public class Util
{
	public Util()
	{
	}

  /// <summary>
  /// Converts a value from the DB to a text string suitable for a text box
  /// </summary>
  public static string ToText(object val)
  {
    if (val is DBNull) return "";
    if (val is INullable && ((INullable)val).IsNull) return "";
    return val.ToString();
  }

  /// <summary>
  /// Converts a string from a textbox to a sqlstring, trimming it first
  /// </summary>
  public static SqlString ToSqlStr(string txt)
  {
    string txt2 = txt.Trim();
    return txt2.Length == 0 ? SqlString.Null : txt2;
  }

  /// <summary>
  /// Escapes a string so it can fit in a csv file
  /// eg if it's got commas or double quotes, then it gets escaped
  /// </summary>
  public static string CsvEscape(string val)
  {
    if (val.Contains(',') || val.Contains('"'))
    {
      val = "\"" + val.Replace("\"", "\"\"") + "\""; // Basically, convert >Blah"Yada,Test< into >"Blah""Yada,Test"<
    }
    return val;
  }

  /// <summary>
  /// Salt the hell out of a string before hashing it
  /// </summary>
  public static string HashAndSalt(string password)
  {
    // Salt it
    string text =
      "Eabsor3k3zFzu5QnKrH4NJfOgV2WWqV5Oc1lTH4BRrEA8z2Nw9BoQ5eS9NW20oK" +
      password +
      "eWk344fgXSo1DMuByokGSDyFPQ0DbXd9rAgWdojiZ5nmaYpt9HT9jW4KPdH5DX4";
    // Hash it
    byte[] clear = Encoding.UTF8.GetBytes(text);
    byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(clear);
    return BitConverter.ToString(hash).Replace("-", "").ToLower();
  }
}
